package com.slz3.business.module.systemManagement.sysRole.service;

import com.slz3.business.frame.enums.ValidFlag;
import com.slz3.business.frame.module.Repositorys;
import com.slz3.business.frame.module.Services;
import com.slz3.business.frame.steward.PageableSteward;
import com.slz3.business.module.systemManagement.sysRole.domain.SysRole;
import com.slz3.business.module.systemManagement.sysRole.domain.SysRoleFactory;
import com.slz3.business.module.systemManagement.sysRole.steward.SysRoleSpecification;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;

import java.util.*;

@Slf4j
@Service
public class SysRoleServiceImpl implements SysRoleService {

    @Override
    public SysRole save(SysRole sysRole) {
        try {
            Repositorys.sysRole.save(SysRoleFactory.initBaseFields(sysRole));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Repositorys.sysRole.save(SysRoleFactory.initBaseFields(sysRole));
    }

    @Override
    public Page<SysRole> page(MultiValueMap<String, String> params) {
        Page<SysRole> sysRolePage = Repositorys.sysRole.findAll(
                SysRoleSpecification.findJoin(params), PageableSteward.extract(params)
        );
        return sysRolePage;
    }

    @Override
    public SysRole modify(SysRole sysRoleNew) {
        return Repositorys.sysRole.saveAndFlush(SysRoleFactory.initBaseFields(sysRoleNew));
    }

    @Override
    public Optional<SysRole> single(UUID uuid) {
        return Repositorys.sysRole.findById(uuid);
    }

    @Override
    public List<SysRole> findAllByUuids(Iterable<UUID> uuids) {
        return Repositorys.sysRole.findAllById(uuids);
    }

    @Override
    public List<SysRole> delete(List<SysRole> sysRoleList) {
        sysRoleList.stream().forEach(item -> {
            item.setValidFlag(ValidFlag.DEL);
            SysRoleFactory.initBaseFields(item);
        });
        return Services.sysRoleTransactional.batchModify(sysRoleList);
    }

    @Override
    public List<SysRole> findAll(SysRole param) {
        param.setValidFlag(ValidFlag.VALID);
        return Repositorys.sysRole.findAll(Example.of(param));
    }
}
